package com.pms.web;
import com.pms.entity.BaseUserInfo;
import com.pms.entity.FrontUser;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.jwt.JwtAuthenticationResponse;
import com.pms.rpc.ILoginLogService;
import com.pms.rpc.IUserService;
import com.pms.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("jwt")
public class AuthController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${gate.jwt.header}")
    private String tokenHeader;

    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);
    @Autowired
    private AuthService authService;
    @Autowired
    private IUserService userService;
    @Autowired
    ILoginLogService loginLogService;
    /**
     * 登录
     * token （由三部分组成 Header(请求头), Claims（要求）,Signature（签名））
     * @param
     * @return
     */
    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(
           String username,String password,String companyCode) {
        BaseUserInfo info = userService.getByuseraccount(username,companyCode);
        if (null==info||null==info.getId()){ throw  new RRException("账号信息不存在",400);}
        if (2==info.getStatus()){ throw  new RRException("该账号已被停用，请联系管理员",400);}
        Map<String,Object> code=userService.getByCompany(info.getCompanyCode());
        if (null==code||null==code.get("id")){ throw  new RRException("公司信息不存在",400);}
        if (Integer.parseInt(code.get("status").toString())==2){ throw  new RRException("该账号所属系统已被禁用,请联系管理员",400);}
        if(encoder.matches(password,info.getPassword())){
            final String token = authService.login(info);
            loginLogService.addLoginLog(info.getId(),info.getName(),"登录成功");
            logger.info("login--token-   "+token);
            Map<String,Object> map= new HashMap<>();
            map.put("token",token);
            map.put("flag",2);
            return ResponseEntity.ok(map);
        }else {
            throw  new RRException("账号密码错误",400);
        }
    }

    /**
     * 刷新token
     * @param request
     * @return
     */
    @RequestMapping(value = "/refresh", method = RequestMethod.GET)
    public ResponseEntity<?> refreshAndGetAuthenticationToken(
            HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String companyCode = request.getHeader("X-Code");
        String name = request.getHeader("X-Name");
        BaseUserInfo info = userService.getByuseraccount(name,companyCode);
        if (null==info){throw  new RRException("输入信息有误，请重新输入",400);}
        String refreshedToken = authService.refresh(token,info);
        if(refreshedToken == null) {
            return ResponseEntity.badRequest().body(null);
        } else {
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
        }
    }

    /**
     * 验证token
     * @param token
     * @param resource
     * @return
     */
    @RequestMapping(value = "/verify", method = RequestMethod.GET)
    public ResponseEntity<?> verify(HttpServletRequest request,String token,String resource){
        String companyCode = request.getHeader("X-Code");
        if(authService.validate(token,resource,null,companyCode))
            return ResponseEntity.ok(true);
        else
            return ResponseEntity.status(401).body(false);
    }

    /**
     * 退出清除token
     * @param token
     * 只是清除缓存中的token
     * @return
     */
    @RequestMapping(value = "/invalid", method = RequestMethod.POST)
    public ResponseEntity<?> invalid(@RequestHeader("X-Token")String token){
        authService.invalid(token);
        return ResponseEntity.ok(true);
    }

    /**
     * 查看用户所拥有的权限
     * @param token
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.GET)
        public R getUserInfo(HttpServletRequest request,String token,Integer menuType){
        if (StringUtils.isEmpty(token)){throw  new RRException("token不能为空",400);}
        if (menuType==null){
            menuType=1;
        }
        String companyCode = request.getHeader("X-Code");
        FrontUser userInfo = authService.getUserInfo(token,menuType,companyCode);
        if(userInfo==null)
            return R.ok().put("data",null);
        else
            return R.ok().put("data",userInfo);
    }

    /**
     * 查询所有
     * @return
     */
    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getAll(){return userService.getAll();
    }


    /**
     * 登录
     * token （由三部分组成 Header(请求头), Claims（要求）,Signature（签名））
     * @param
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity<?> login(
            String username,String password) {
        BaseUserInfo info = userService.getBySuperUser(username);
        if (null==info||null==info.getId()){ throw  new RRException("账号信息不存在",400);}
        if (21!=info.getType()){ throw  new RRException("该账号不属于超级管理员，请从新输入",400);}
        if (2==info.getStatus()){ throw  new RRException("该账号已被停用，请联系管理员",400);}
        if(encoder.matches(password,info.getPassword())){
            final String token = authService.login(info);
            loginLogService.addLoginLog(info.getId(),info.getName(),"超级管理员登录成功");
            logger.info("login--token-   "+token);
            Map<String,Object> map= new HashMap<>();
            map.put("token",token);
            map.put("flag",1);
            return ResponseEntity.ok(map);
        }else {
            throw  new RRException("账号密码错误",400);
        }
    }
    /**
     * 获取超级管理员的权限
     * @param token
     * @return
     */
    @RequestMapping(value = "/superUser", method = RequestMethod.GET)
    public R getSuperUser(String token){
        if (StringUtils.isEmpty(token)){throw  new RRException("token不能为空",400);}
        FrontUser userInfo = authService.getSuperUser(token);
        if(userInfo==null)
            return R.ok().put("data",null);
        else
            return R.ok().put("data",userInfo);
    }

}
